//
//  VCItemEditViewController.m
//  VideoCollage
//
//  Created by Mac on 2018/6/22.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "VCItemEditViewController.h"
#import "VCMusicListViewController.h"
#import "VCAssetChosedViewController.h"
#import "STWebViewController.h"
#import "AVAsset+STTools.h"
#import "NSBundle+STSystemTool.h"
#import <AVFoundation/AVFoundation.h>
#import "XFCameraController.h"
#import "VideoBuilder.h"
#import "VCSizeChosedViewController.h"
#import "VCImagePickerTool.h"
@interface VCItemEditViewController ()<VCItemViewDelegate>
@property(nonatomic, strong) UIScrollView                         *scrollView;/**< scrollView */
@property(nonatomic, strong) VCItemView                           *itemView;/**< itemView */
@property(nonatomic, strong) UIView                               *footerView;/**< foter */
@property(nonatomic, strong) STMenuControl                        *musicControl;/**< musicControl */

@property(nonatomic, strong) NSString                             *musciPath;/**< 音乐path */
@property(nonatomic, assign) bool                                  isMergeMusci;/**< 是否合成了音乐 */
@property(nonatomic, strong) STButton                             *saveButton;/**< 保存按钮 */

@property(nonatomic, strong) VCImagePickerTool                     *imagePickerTool;/**< <##> */
@end

@implementation VCItemEditViewController
- (void)dealloc{
    DDLogInfo(@"VCItemEditViewController dealloc");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectedModels = NSMutableArray.new;
    [self configSubView];
    [self st_setRightItemWithImage:[UIImage imageNamed:@"pic-red"]];
    
    
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.itemView.assetModles = self.selectedModels;
}
- (void)setSelectedModels:(NSMutableArray<TZAssetModel *> *)selectedModels{
    _selectedModels = selectedModels;
    self.finshPath = nil;
}
#pragma mark --subView
- (void)configSubView{
    

    
    __weak typeof(self) weakSelf =  self;
    
    self.view.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:UIScreenFrame andColors:@[FlatOrange,FlatCoffee,FlatMint]];
    self.view.backgroundColor = TM_backgroundColor;
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight)];
    self.scrollView.backgroundColor = TM_backgroundColor;
    [self.view addSubview:self.scrollView];
    self.itemView = [[VCItemView alloc] initWithRank:self.rank];
    self.itemView.top = 0 + 47;
    self.itemView.layer.cornerRadius = 4;
    self.itemView.clipsToBounds = YES;
    [self.itemView setDelegate:self];
    [self.scrollView addSubview:self.itemView];
    CGFloat itemWith = UIScreenWidth *0.8;
    CGRect finshFrame = CGRectMake((UIScreenWidth - itemWith)/2, 47, itemWith, itemWith);
    self.itemView.frame = finshFrame;
    [self.itemView updateItemFrame];
    
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(10, self.itemView.top + 0.5 * self.itemView.height, UIScreenWidth - 20, 341)];
    footer.backgroundColor = UIColor.clearColor;
    [self.scrollView addSubview:footer];
    
    
    CGFloat whiteHeight = 90;
    CGFloat redHeight = self.itemView.height / 2;
    UIView * redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, footer.width, redHeight + whiteHeight)];
    redView.backgroundColor = TM_redColor;
    redView.clipsToBounds = YES;
    redView.layer.cornerRadius = 4;
    [footer addSubview:redView];
    
    UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, redView.bottom - whiteHeight/2,redView.width , whiteHeight)];
    whiteView.backgroundColor = UIColor.whiteColor;
    whiteView.clipsToBounds = YES;
    whiteView.layer.cornerRadius = whiteHeight/2;
    [footer addSubview:whiteView];
    //菜单
    CGFloat itemWitdh = whiteView.width/3;
    STMenuControl * editorControl = [[STMenuControl alloc] initWithFrame:CGRectMake(0, 0, itemWitdh, whiteHeight) imageName:@"editor-1" title:@"Editor" titleColor:SecendTextColor];
    [editorControl setOnSelctedControl:^(STMenuControl *control) {
        [weakSelf onSletcedEditorButton];
    }];
    [editorControl.titleButton setImage:[UIImage imageNamed:@"editor-2"] forState:UIControlStateHighlighted];
    [whiteView addSubview:editorControl];
    
    STMenuControl * MusicControl = [[STMenuControl alloc] initWithFrame:CGRectMake(0, 0, itemWitdh, whiteHeight) imageName:@"music-1" title:@"Music" titleColor:SecendTextColor];
    [MusicControl setOnSelctedControl:^(STMenuControl *control) {
        [weakSelf onSletcedMusicButton];
    }];
    MusicControl.centerX = whiteView.width/2;
    self.musicControl = MusicControl;
    [MusicControl.titleButton setImage:[UIImage imageNamed:@"music-2"] forState:UIControlStateHighlighted];
    [whiteView addSubview:MusicControl];
    
    
    STMenuControl * PreviewControl = [[STMenuControl alloc] initWithFrame:CGRectMake(0, 0, itemWitdh, whiteHeight) imageName:@"preview-1" title:@"Preview" titleColor:SecendTextColor];
    [PreviewControl setOnSelctedControl:^(STMenuControl *control) {
        [weakSelf onSletcedPreviewButton];
    }];
    [PreviewControl.titleButton setImage:[UIImage imageNamed:@"preview-2"] forState:UIControlStateHighlighted];
    PreviewControl.left = 2*itemWitdh;
    [whiteView addSubview:PreviewControl];
    //
    
    STButton * saveButton = [[STButton alloc] initWithFrame:CGRectMake(0, whiteView.bottom + 60, 150, 44)
                                                      title:@"save"
                                                 titleColor:UIColor.whiteColor
                                                  titleFont:16
                                               cornerRadius:22
                                            backgroundColor:TM_redColor
                                            backgroundImage:nil
                                                      image:nil];
    [footer addSubview:saveButton];
    footer.height = saveButton.bottom + 60;
    [saveButton setClicAction:^(UIButton *sender) {
        [weakSelf onSletcedSaveButton];
    }];
    saveButton.centerX = footer.width/2;
    saveButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.saveButton = saveButton;
    [self.scrollView bringSubviewToFront:self.itemView];
    self.footerView = footer;
    
    self.scrollView.contentSize = CGSizeMake(0, footer.bottom);
    
    
    
    //在view 右上角放一个透明的view 以用于 ipad popcontroller;
    self.popView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    self.popView.bottom = TMUtils.navgationBarBootom + 44;
    self.popView.backgroundColor = UIColor.clearColor;
    self.popView.right = UIScreenWidth - 10;
    [self.view addSubview:self.popView];
}
- (void)updateFrameWithItemFrame:(CGRect)itemFrame{
    self.itemView.frame = itemFrame;
    self.itemView.top = 47;
    self.footerView.top = self.itemView.top + 0.33 * self.itemView.height;
    self.scrollView.contentSize = CGSizeMake(0, self.footerView.bottom);
}
#pragma mark --VCItemViewDelegate
- (void)onSlectedView:(VCItemView*)view item:(UIButton*)item{
    VCAssetChosedViewController * vc = VCAssetChosedViewController.defult;
    vc.rank = self.rank;
    vc.selectedModels = self.selectedModels;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    DDLogInfo(@"点击了拍摄");
    [self gotoTakePhoto];
    
}
- (void)gotoTakePhoto{
    if (self.itemView.itemImageViewArray.count == self.selectedModels.count) {
        [SVProgressHUD showInfoWithStatus:@"More than the maximum number of selected sheets"];
        return;
    }
    [self takePhoto_ipad];
    return;
    NSString* phoneModel = [[STMonitorCrashManger defult] iphoneType];
    bool isIos_10_3 = ([UIDevice currentDevice].systemVersion.floatValue >= 10.3) && ([UIDevice currentDevice].systemVersion.floatValue < 10.4);
    if ([phoneModel containsString:@"iPad"] || isIos_10_3) {
        [self takePhoto_ipad];
    }else{
        [self takeNormalPhoto];
    }
    

}
- (void)takeNormalPhoto{
    XFCameraController *cameraController = [XFCameraController defaultCameraController];
    __weak XFCameraController *weakCameraController = cameraController;
    cameraController.takePhotosCompletionBlock = ^(UIImage *image, NSError *error,NSString * assetID) {
        DDLogInfo(@"takePhotosCompletionBlock");
        dispatch_async(dispatch_get_main_queue(), ^{
            PHAsset * asset =  [[PHAsset fetchAssetsWithLocalIdentifiers:@[assetID] options:nil] firstObject];
            TZAssetModel * model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhoto];
            VCImageView * imageView = self.itemView.nearNoresultImageView;
            imageView.image = image;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[TZImageManager manager] getOriginalPhotoWithAsset:model.asset completion:^(UIImage *photo, NSDictionary *info) {
                    DDLogInfo(@"获取原图info = %@",info);
                    if (![info[PHImageResultIsDegradedKey] boolValue]) {
                        //原图
                        dispatch_async(dispatch_get_main_queue(), ^{
                            model.assetID = assetID;
                            model.cachedImage = photo;
                            [imageView setImage:photo];
                            [self.selectedModels addObject:model];
                            self.selectedModels = self.selectedModels;
                            self.itemView.assetModles = self.selectedModels;
                            [imageView st_setDottedLineBrderWidth:1 borderColor:UIColor.clearColor];
                            [weakCameraController dismissViewControllerAnimated:YES completion:nil];
                            [SVProgressHUD dismiss];
                        });
                    }
                }];
            });
        });
    };
    
    cameraController.shootCompletionBlock = ^(NSURL *videoUrl, CGFloat videoTimeLength, UIImage *thumbnailImage, NSError *error,NSString * assetID) {
        DDLogInfo(@"shootCompletionBlock");
        dispatch_async(dispatch_get_main_queue(), ^{
            PHAsset * asset =  [[PHAsset fetchAssetsWithLocalIdentifiers:@[assetID] options:nil] firstObject];
            TZAssetModel * model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo];
            VCImageView * imageView = self.itemView.nearNoresultImageView;
            imageView.image = thumbnailImage;
            //更换方法
            [[TZImageManager manager] getPhotoWithAsset:model.asset photoWidth:200 completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                DDLogInfo(@"获取缩略图成功 photo= %@ info = %@",
                          photo,info.description);
                model.assetID = assetID;
                model.cachedImage = photo;
                if (![self.selectedModels containsObject:model]) {
                    [self.selectedModels addObject:model];
                    self.selectedModels = self.selectedModels;
                    self.itemView.assetModles = self.selectedModels;
                }
                [imageView st_setDottedLineBrderWidth:1 borderColor:UIColor.clearColor];
                [weakCameraController dismissViewControllerAnimated:YES completion:nil];
                [SVProgressHUD dismiss];
                imageView.image = photo;
            }];
        });
    };
    
    [self presentViewController:cameraController animated:YES completion:nil];
}
- (void)takePhoto_ipad{
    __weak typeof(self) weakSelf =  self;
    self.imagePickerTool = [[VCImagePickerTool alloc] initWithFormViewController:self];
    [self.imagePickerTool setTakePhotosCompletionBlock:^(UIImage *image, NSError *error, NSString *assetID) {
        DDLogInfo(@"takePhotosCompletionBlock");
        dispatch_async(dispatch_get_main_queue(), ^{
            PHAsset * asset =  [[PHAsset fetchAssetsWithLocalIdentifiers:@[assetID] options:nil] firstObject];
            TZAssetModel * model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhoto];
            VCImageView * imageView = weakSelf.itemView.nearNoresultImageView;
            imageView.image = image;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[TZImageManager manager] getOriginalPhotoWithAsset:model.asset completion:^(UIImage *photo, NSDictionary *info) {
                    DDLogInfo(@"获取原图info = %@",info);
                    if (![info[PHImageResultIsDegradedKey] boolValue]) {
                        //原图
                        dispatch_async(dispatch_get_main_queue(), ^{
                            model.assetID = assetID;
                            model.cachedImage = photo;
                            [imageView setImage:photo];
                            [self.selectedModels addObject:model];
                            self.selectedModels = self.selectedModels;
                            self.itemView.assetModles = self.selectedModels;
                            [imageView st_setDottedLineBrderWidth:1 borderColor:UIColor.clearColor];
                            //[weakCameraController dismissViewControllerAnimated:YES completion:nil];
                            [SVProgressHUD dismiss];
                        });
                    }
                }];
            });
        });
    }];
    [self.imagePickerTool setShootCompletionBlock:^(NSURL *videoUrl, CGFloat videoTimeLength, UIImage *thumbnailImage, NSError *error, NSString *assetID) {
        DDLogInfo(@"shootCompletionBlock");
        dispatch_async(dispatch_get_main_queue(), ^{
            PHAsset * asset =  [[PHAsset fetchAssetsWithLocalIdentifiers:@[assetID] options:nil] firstObject];
            TZAssetModel * model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo];
            VCImageView * imageView = weakSelf.itemView.nearNoresultImageView;
            imageView.image = thumbnailImage;
            //更换方法
            [[TZImageManager manager] getPhotoWithAsset:model.asset photoWidth:200 completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                DDLogInfo(@"获取缩略图成功 photo= %@ info = %@",
                          photo,info.description);
                model.assetID = assetID;
                model.cachedImage = photo;
                if (![self.selectedModels containsObject:model]) {
                    [self.selectedModels addObject:model];
                    self.selectedModels = self.selectedModels;
                    self.itemView.assetModles = self.selectedModels;
                }
                [imageView st_setDottedLineBrderWidth:1 borderColor:UIColor.clearColor];
                [SVProgressHUD dismiss];
                imageView.image = photo;
            }];
        });
    }];
    [self.imagePickerTool show];
    return;
}
- (void)onSletcedSaveButton{
    DDLogInfo(@"点击了保存");
    if (!self.finshPath) {
        [SVProgressHUD showInfoWithStatus:@"Please preview before generating"];
        return;
    }
    NSString * path = self.finshPath;
    NSURL *urlToShare = [NSURL fileURLWithPath:path];
    NSArray *activityItems = @[urlToShare];
    UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    [controller setCompletionWithItemsHandler:^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (activityError) {
            [SVProgressHUD showErrorWithStatus:activityError.description];
        }
    }];
    //防止ipad crash
    UIPopoverPresentationController *popover = controller.popoverPresentationController;
    if (popover) {
        popover.sourceView = self.saveButton;
        popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
    }
    [self presentViewController:controller animated:YES completion:nil];
    
}
- (void)onSletcedEditorButton{
    DDLogInfo(@"点击了编辑");
    VCSizeChosedViewController * vc = [VCSizeChosedViewController new];
    vc.currentModel = self.itemView.sizeModel;
    [vc setDidSelctedSizeHandle:^(VCItemSizeModel *model) {
        self.finshPath = nil;
        self.itemView.sizeModel = model;
        if (model.isSizeChanged) {
            [UIView animateWithDuration:0.3 animations:^{
                [self.itemView updateItemFrame];
            }];
            
        }else{
            [self.itemView updateItemFrame];
        }
        
    }];
    [self presentViewController:vc animated:NO completion:nil];
    
}
- (void)onSletcedMusicButton{
    DDLogInfo(@"点击了音乐");
    VCMusicListViewController * vc = [VCMusicListViewController new];
    [vc setOnSelctedMusciHandle:^(NSString *musicName, NSString *path) {
        if ([self.musciPath isEqualToString:path]) {
            
        }else{
            // 更新过选择的音乐
            self.musciPath = path;
            self.itemView.musicPah = path;
            self.isMergeMusci = NO;
            DDLogInfo(@"音乐:%@   path:%@",musicName,path);
        }
        
    }];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)onSletcedPreviewButton{
    if (self.finshPath) {
        //已经合成过资源
        if ([self.finshPath containsString:@"mp4"]) {
            //当前资源是视频
            if (self.musciPath.length && !self.isMergeMusci) {
                //存在音乐 且 没有合成过 则视频+音乐合成视频
                [self meargeMusci];
            }
            if (!self.musciPath.length && !self.isMergeMusci) {
                //没有选音乐 预览视频
                [self goVideoPreviewWithPath:self.finshPath];
            }
            if (self.musciPath.length && self.isMergeMusci) {
                //音乐没有更新 则预览
                [self goVideoPreviewWithPath:self.finshPath];
            }
        }
        if ([self.finshPath containsString:@"png"]) {
            //当前资源是图片
            if (self.musciPath.length && !self.isMergeMusci) {
                //存在音乐 且 没有合成过 则图片+音乐合成视频
                //生成音乐
                [SVProgressHUD showWithStatus:@"Merging is under way, please wait"];
                UIImage * image = [UIImage imageWithContentsOfFile:self.finshPath];
                [[VCAssetCreatManger manger] meargeImageToVideoPathView:self.itemView image:image progress:^(CGFloat persent) {
                    
                } handle:^(bool success, NSError *error, NSString *path, UIImage *image) {
                    if (success) {
                        self.finshPath = path;
                        [VCAssetCreatManger manger].isImageToVideo = YES;
                        [self meargeMusci];
                        [VCAssetCreatManger manger].isImageToVideo = NO;
                        
                    }
                }];
                
            }
            if (self.musciPath.length && self.isMergeMusci) {
                //存在音乐 且 合成过 则预览视频
                [self goVideoPreviewWithPath:self.finshPath];
            }
            if (!self.musciPath.length && !self.isMergeMusci) {
                // 没有选择音乐 且 没有合成音乐   预览图片
                [self goLookImageViewWithPath:self.finshPath];
            }
        }
        
    }else if (self.itemView.assetModles.count) {
        //没有合成过
        [SVProgressHUD showWithStatus:@"Merging is under way, please wait"];
        [[VCAssetCreatManger manger] cgreateAssetWithView:self.itemView progress:^(CGFloat persent) {
            
        } handle:^(bool success, NSError *error, NSString *path,UIImage * image) {
            //[SVProgressHUD dismiss];
            if (success && path.length) {
                
                self.finshPath = path;
                //合成的是图片
                if (image) {
                    //选择的图片且 选择了音乐 则图片+音乐 转视频
                    if (self.musciPath.length) {
                        NSMutableArray *images = [NSMutableArray new];
                        for (NSInteger i =0 ; i <24 * 5; i ++) {
                            [images addObject:image];
                        }
                        [[VCAssetCreatManger manger] meargeImageToVideoPathView:self.itemView image:image progress:^(CGFloat persent) {
                            
                        } handle:^(bool success, NSError *error, NSString *path, UIImage *image) {
                            if (success) {
                                self.finshPath = path;
                                [VCAssetCreatManger manger].isImageToVideo = YES;
                                [self meargeMusci];
                                [VCAssetCreatManger manger].isImageToVideo = NO;
                                
                            }
                        }];
                        
                    }else{
                        //选择的图片且 没有音乐 则生成图片
                        [SVProgressHUD dismiss];
                        [self goLookImageViewWithPath:path];
                    }
                    
                    
                }else{
                    //合成的 结果是视频
                    if (self.musciPath) {
                        //合成的 结果是视频 且选择了音乐 则合成音乐 + 视频
                        [self meargeMusci];
                    }else{
                        //合成的 结果是视频 且没有音乐 则预览视频
                        [self goVideoPreviewWithPath:path];
                    }
                    
                }
                
            }
        }];
    }else{
        //什么都没有选择
        [SVProgressHUD showInfoWithStatus:@"Please select resources"];
    }
}
#pragma mark --Private Method
//获取视频第一针 图片 iphone 6 ios 9 无法获取原图
- (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        DDLogInfo(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
    
    return thumbnailImage;
}
- (void)goLookImageViewWithPath:(NSString*)path{
    DDLogInfo(@"预览图片 %@",path);
    VCPhotoLookViewController * vc = VCPhotoLookViewController.new;
    vc.imagePath    = path;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)goVideoPreviewWithPath:(NSString*)parh{
    DDLogInfo(@"预览视频 %@",parh);
    VCVideoLookViewController * vc = VCVideoLookViewController.new;
    vc.path = parh;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)meargeMusci{
    [SVProgressHUD showWithStatus:@"Music is being merged, please wait"];
    [[VCAssetCreatManger manger] meargeAssetWithLocalVideoPath:self.finshPath musicPatth:self.musciPath progress:^(CGFloat persent) {
        
    } handle:^(bool success, NSError *error, NSString *path, UIImage *image) {
        if (success && path.length) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showSuccessWithStatus:@"Merger success"];
            self.finshPath = path;
            self.isMergeMusci = YES;
            [self goVideoPreviewWithPath:self.finshPath];
        }
    }];
}

@end

